package com.catmiao.spark.sql.test

import org.apache.spark.SparkConf
import org.apache.spark.sql.expressions.Aggregator
import org.apache.spark.sql._

/**
 * @title: Spark01_sql_test01
 * @projectName spark_study
 * @description: TODO
 * @author ChengMiao
 * @date 2024/3/20 10:44
 */
object Spark04_sql_JDBC {

  def main(args: Array[String]): Unit = {
    val sparkConf: SparkConf = new SparkConf().setMaster("local[*]").setAppName("spark_sql_01_test")

    // 创建 Spark Session对象
    val sparkSession: SparkSession = SparkSession.builder().config(sparkConf).getOrCreate()
    // 涉及转换操作，需要引入转换规则
    import sparkSession.implicits._

    // 读取mysql的数据
    val df = sparkSession.read
      .format("jdbc")
      .option("url","jdbc:mysql://localhost:3306/test_db")
      .option("driver","com.mysql.jdbc.Driver")
      .option("user","root")
      .option("password","1234")
      .option("dbtable","student")
      .load()
//      .show()

    // 保存数据
    df.write
      .format("jdbc")
      .option("url", "jdbc:mysql://localhost:3306/test_db")
      .option("driver", "com.mysql.jdbc.Driver")
      .option("user", "root")
      .option("password", "1234")
      .option("dbtable", "student_copy")
      .mode(SaveMode.Append)
      .save()



    // 关闭环境
    sparkSession.close()
  }



}

